import { useEffect, useState } from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import { Button, Modal, Tag } from "antd";
import {CloseOutlined, SearchOutlined} from "@ant-design/icons";
import PagePermissionSelect from "./pagePermissionSelect";
// 引入 antd 的图标用于 Tag 关闭按钮（可选，根据需要开启）
// import { CloseOutlined } from "@ant-design/icons";

/**
 * 分配角色页面权限模态框组件
 * 功能：展示并管理角色已有的页面权限，支持提交保存
 */
const RolePageAllocate = (props) => {
    const {
        messageApi,
        editModalVisible,
        setEditModalVisible,
        roleId,
        existConsolePages,
        searchRoleById
    } = props;

    // 存储当前选中的页面权限列表（用于展示和提交）
    const [consolePages, setConsolePages] = useState([]);

    // 页面权限选择模态框开关
    const [pageSelectVisible, setPageSelectVisible] = useState(false);

    /**
     * 为角色分配页面权限
     * 调用接口提交选中的页面权限，成功后刷新数据并关闭模态框
     */
    const allocateRolePagePermission = () => {
        RequestUtils.post(RequestApis.permissionManage.allocateRolePagePermission, {
            roleId: roleId,
            pageCodes: consolePages.map(v => v.pageCode)
        }).then(res => {
            searchRoleById();
            messageApi.success("页面权限分配成功");
            setEditModalVisible({
                ...editModalVisible,
                editPagePermission: false
            });
        }).catch(err => messageApi.error(err.message));
    };

    /**
     * 模态框打开时加载数据
     * 监听 editPagePermission 状态，当模态框打开时同步已有权限数据
     */
    useEffect(() => {
        if (editModalVisible.editPagePermission) {
            setConsolePages(existConsolePages);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [editModalVisible.editPagePermission]);

    return (
        <Modal
            open={editModalVisible.editPagePermission}
            title="为角色分配页面访问权限"
            width={600}
            onCancel={() => {
                setEditModalVisible({
                    ...editModalVisible,
                    editPagePermission: false
                });
            }}
            footer={
                <div>
                    <Button
                        type="primary"
                        onClick={() => allocateRolePagePermission()}
                    >
                        确认
                    </Button>
                    <Button
                        danger
                        style={{ marginLeft: "12px" }}
                        onClick={() => {
                            setEditModalVisible({
                                ...editModalVisible,
                                editPagePermission: false
                            });
                        }}
                    >
                        取消
                    </Button>
                </div>
            }
        >
            {/* 权限展示区域容器 */}
            <div style={containerStyle}>
                <div>
                    <Button
                        color='purple'
                        variant='solid'
                        onClick={() => setPageSelectVisible(true)}>
                        <SearchOutlined  style={{marginRight: '4px'}}/>
                        选择页面权限
                    </Button>
                </div>

                {/* 标题区域 */}
                <div style={titleStyle}>
                    当前已选页面权限
                    <span style={countStyle}>({consolePages.length})</span>
                </div>

                {/* Tag 展示区域 */}
                <div style={tagListStyle}>
                    {consolePages.length > 0 ? (
                        consolePages.map(v => (
                            <Tag
                                key={v.pageCode}
                                style={tagStyle}
                            >
                                {v.pageName}
                                <CloseOutlined
                                    style={{marginLeft: '8px'}}
                                    onClick={() => {
                                        setConsolePages(consolePages.filter(item => item.pageCode !== v.pageCode));
                                    }}
                                />
                            </Tag>
                        ))
                    ) : (
                        <div style={emptyStyle}>暂无已选页面权限</div>
                    )}
                </div>
            </div>

            {/* 权限选择模态框 */}
            <PagePermissionSelect
                visible={pageSelectVisible}
                setVisible={setPageSelectVisible}
                consolePages={consolePages}
                setConsolePages={setConsolePages}
            />

        </Modal>
    );
};

// 样式定义：使用对象形式集中管理，便于维护
const containerStyle = {
    padding: "16px",
    backgroundColor: "#f5f7fa", // 浅灰背景提升层次感
    borderRadius: "8px",
    marginTop: "8px"
};

const titleStyle = {
    fontSize: "14px",
    fontWeight: 600, // 加粗标题
    color: "#1f2329",
    marginBottom: "12px",
    display: "flex",
    alignItems: "center",
    marginTop: '12px'
};

const countStyle = {
    fontSize: "12px",
    fontWeight: 400,
    color: "#6b7280",
    marginLeft: "8px",
    backgroundColor: "#e5e7eb",
    padding: "2px 8px",
    borderRadius: "12px"
};

const tagListStyle = {
    display: "flex",
    flexWrap: "wrap", // 自动换行
    gap: "8px", // 标签间距
    marginTop: "8px"
};

const tagStyle = {
    padding: "4px 12px",
    fontSize: "13px",
    borderRadius: "16px", // 圆角更柔和
    backgroundColor: "#e8f4fd", // 浅蓝色背景
    color: "#1677ff", // 蚂蚁蓝文字
    borderColor: "#bfdbfe",
    transition: "all 0.2s",
    cursor: "default",
    // 悬停效果
    "&:hover": {
        backgroundColor: "#d1eaff"
    }
};

const emptyStyle = {
    fontSize: "13px",
    color: "#6b7280",
    padding: "16px",
    textAlign: "center",
    backgroundColor: "#ffffff",
    borderRadius: "6px",
    width: "100%"
};

export default RolePageAllocate;